import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import jwtDecode from 'jwt-decode'
const dataOne = {
  EnterTimeStart: null,
  EnterTimeEnd: null,
  status: false
}
const adminObj = {
  isAdmin: true,
  roles: 'user',
  IsSupper: false
}
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    roles: [],
    // 报警消息默认值
    selectValue: 0,
    // 重置
    changeValue: 0,
    // 表单是否有值
    formValue: {},
    // 搜索框部门改变
    departmentValue: '',
    // 是否进入实时定位页面
    pageData: false,
    // 考勤统计时间
    attendanceDate: dataOne,
    editStatus: {},
    // 隧道编码
    code: JSON.parse(localStorage.getItem('code')),
    // 是否是管理员
    adminObj: JSON.parse(localStorage.getItem('adminObj')) || adminObj,
    showId: JSON.parse(localStorage.getItem('showId')),
    oneLevel: JSON.parse(localStorage.getItem('oneLevel')),
    // 展示闸机数据
    gateSwaitch: JSON.parse(localStorage.getItem('gateSwaitch')) || '展示',
    // 选中的一级菜单
    activeOne: JSON.parse(localStorage.getItem('activeOne')) || '',
    // 选中的二级菜单
    activeTwo: JSON.parse(localStorage.getItem('activeTwo')) || '',
    codeList: [],
    idList: JSON.parse(localStorage.getItem('idList')) || []
  }
}

const state = getDefaultState()

const mutations = {
  // 保存
  SET_AOPETIONONE: (state, data) => {
    state.activeOne = data

    localStorage.setItem('activeOne', JSON.stringify(state.activeOne))
  },
  SET_AOPETIONTWO: (state, data) => {
    state.activeTwo = data

    localStorage.setItem('activeTwo', JSON.stringify(state.activeTwo))
  },
  // 展示闸机数据
  SET_GATESWAITCH: (state, gateSwaitch) => {
    state.gateSwaitch = gateSwaitch
    localStorage.setItem('gateSwaitch', JSON.stringify(gateSwaitch))
  },
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_ADMINOBJ: (state, adminObj) => {
    if (adminObj.isAdmin) {
      state.adminObj = adminObj
      localStorage.setItem('adminObj', JSON.stringify(state.adminObj))
    } else if (adminObj.IsSupper) {
      state.adminObj = adminObj
      localStorage.setItem('adminObj', JSON.stringify(state.adminObj))
    } else {
      state.adminObj.isAdmin = false
      state.adminObj.roles = adminObj.roles
      localStorage.setItem('adminObj', JSON.stringify(state.adminObj))
    }
  },
  SET_SHOWID: (state, showId) => {
    state.showId = showId
    localStorage.setItem('showId', JSON.stringify(showId))
  },
  SET_ONELEVEL: (state, oneLevel) => {
    state.oneLevel = oneLevel
    localStorage.setItem('oneLevel', JSON.stringify(oneLevel))
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_SELECTVALUE: (state, selectValue) => {
    state.selectValue = selectValue
  },
  SET_CHANGEVALUE: (state, changeValue) => {
    state.changeValue = changeValue
  },
  SET_EDITSTATUS: (state, value) => {
    state.editStatus = value
  },
  SET_FORMVALUE: (state, formValue) => {
    state.formValue = formValue
  },
  SET_PAGEDATA: (state, pageData) => {
    state.pageData = pageData
  },
  SET_DEPARTMENTVALUE: (state, departmentValue) => {
    state.departmentValue = departmentValue
  },
  SET_ATTENDANCEDATE: (state, attendanceDate) => {
    state.attendanceDate = attendanceDate
  },
  SET_CODE: (state, code) => {
    state.code = code
    localStorage.setItem('code', JSON.stringify(code))
  },
  SET_CODELIST: (state, codeList) => {
    state.codeList = codeList
  },
  SET_IDLIST: (state, idList) => {
    state.idList = idList
    localStorage.setItem('idList', JSON.stringify(idList))
  }
}

const actions = {
  setIdList({ commit }, data) {
    return new Promise((resolve, reject) => {
      const valueList = data.map(item => {
        return item.id.toString()
      })
      commit('SET_IDLIST', valueList)
      resolve()
    })
  },
  setCodeList({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_CODELIST', data)
      resolve()
    })
  },
  setOpentionOne({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_AOPETIONONE', data)
      resolve()
    })
  },
  setOpentionTwo({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_AOPETIONTWO', data)
      resolve()
    })
  },
  setGateSwaitch({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_GATESWAITCH', data)
      resolve()
    })
  },
  // 部门改变，修改职位用到
  setShowId({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_SHOWID', data)
      resolve()
    })
  },
  //
  setOneLevel({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_ONELEVEL', data)
      resolve()
    })
  },
  // 设置当前在那个端
  setAdminObj({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_ADMINOBJ', data)
      resolve()
    })
  },
  //
  setCode({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_CODE', data)
      resolve()
    })
  },
  //
  setAttendanceDate({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_ATTENDANCEDATE', data)
      resolve()
    })
  },
  // 部门改变，修改职位用到
  setDepartmentValue({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_DEPARTMENTVALUE', data)
      resolve()
    })
  },
  // 进出实时定位页面
  setPageData({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_PAGEDATA', data)
      resolve()
    })
  },
  // 表单的值
  setFormValue({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_FORMVALUE', data)
      resolve()
    })
  },
  setChangeValue({ commit, state }) {
    return new Promise((resolve, reject) => {
      const data = state.changeValue + 1
      commit('SET_CHANGEVALUE', data)
      resolve()
    })
  },
  // user login
  login({ commit }, userInfo) {
    const { username, password, validationCode } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: username.trim(), password: password, validationCode: validationCode.trim() })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          const token = jwtDecode(state.token)
          // 登录首先进入概览界面
          console.info('token', token)
          commit('SET_ADMINOBJ', { Logo: token.user.Logo, isAdmin: token.user.IsAdmin, IsSupper: token.user.IsSupper, roles: 'user' })
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const data = jwtDecode(state.token)
      // console.info('getInfo', data)
      data.user.roles = data.user.IsAdmin ? ['admin'] : ['user']
      if (data.user.IsSupper) {
        data.user.roles = ['supper']
      }
      commit('SET_ROLES', data.user.roles)
      commit('SET_NAME', data.user.FirstName)

      resolve(data.user)
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('SET_ADMINOBJ', {})
      commit('RESET_STATE')
      commit('SET_SHOWID', '')
      commit('SET_CODE', '')
      commit('SET_ONELEVEL', '')
      commit('SET_AOPETIONONE', '')
      commit('SET_AOPETIONTWO', '')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  // 设置报警消息默认值
  setDefult({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_SELECTVALUE', data)
      resolve()
    })
  },
  setEdit({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_EDITSTATUS', data)
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
